import Quantize from "quantize";
import Potrace from "potrace";
import Canvas from "canvas";
import { placeOptions,colorOptions } from "@/utils/options/colors.js";


import { random_string,parseToDOM } from "../utils/common.js";
// import { gap } from "./quantize-gap.js";
// import { slicTest } from "./slic.js";
// import { loadLocalImage } from "./ResourceLoader.js";
import { colorDistance, colorRgb,colorHex,hexToRgb,rgbToHex,  getNearColorIndex ,findClosestColor} from "./ColorUtils.js";

// 位图转为矢量图
const getSvgPath = (width, height, buffer, color) => {
    const option = {
        turnPolicy: Potrace.Potrace.TURNPOLICY_MINORITY, // - how to resolve ambiguities in path decomposition (default Potrace.TURNPOLICY_MINORITY)
        turdSize: 5, // - suppress speckles of up to this size (default 2)
        alphaMax: 1, // - corner threshold parameter (default 1)
        optCurve: true, // - curve optimization (default true)
        optTolerance: 0.2, // - curve optimization tolerance (default 0.2)
        threshold: 200, // - threshold below which color is considered black (0..255, default Potrace.THRESHOLD_AUTO)
        blackOnWhite: true, // - specifies colors by which side from threshold should be traced (default true)
        width: width,
        height: height,
        color: color, // - foreground color (default: 'auto' (black or white)) Will be ignored when exporting as <symbol>
        background: "transparent", // - background color (default: 'transparent') Will be ignored when exporting as <symbol>
    };

    return new Promise((resolve, reject) => {
        const potrace = new Potrace.Potrace(option);
        potrace.loadImage(buffer, err => {
            if (err) {
                reject(err);
            } else {
                resolve(potrace.getPathTag());
            }
        });
    });
};

// 提取像素点
const getImageData = image => {
    const canvas = Canvas.createCanvas(image.width, image.height);
    // const canvas = document.createElement('canvas')
    // canvas.width = image.width;
    // canvas.height = image.height;
    const ctx = canvas.getContext("2d");
    // 粘贴图片
    // ctx.filter = 'blur(1px) contrast(1.8)'; // 使用 CSS filter 属性实现模糊处理（如果支持）
    ctx.drawImage(image, 0, 0, image.width, image.height);

    // 模糊+锐化
    // applySharpen(ctx,image.width, image.height)
    // 提取像素点
    const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;

    return pixels;
};

// 将图片进行模糊+锐化

function applySharpen(context, width, height) {
    // 获取原始图像数据
    let originalImageData = context.getImageData(0, 0, width, height);
    let originalPixels = originalImageData.data;

    // 创建一个用于存放处理后的图像数据的 ImageData 对象
    let outputImageData = context.createImageData(width, height);
    let outputPixels = outputImageData.data;

    const kernel = [
        0, -1, 0,
        -1, 5, -1,
        0, -1, 0,
    ];

    const kernelSize = Math.sqrt(kernel.length);
    const halfKernelSize = Math.floor(kernelSize / 2);

    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            let r = 0, g = 0, b = 0;

            for (let ky = 0; ky < kernelSize; ky++) {
                for (let kx = 0; kx < kernelSize; kx++) {
                    // 考虑边缘像素
                    let pixelY = y + ky - halfKernelSize;
                    let pixelX = x + kx - halfKernelSize;

                    if (pixelY < 0 || pixelY >= height || pixelX < 0 || pixelX >= width) continue;

                    // 卷积计算
                    let offset = (pixelY * width + pixelX) * 4;
                    let weight = kernel[ky * kernelSize + kx];

                    r += originalPixels[offset] * weight;
                    g += originalPixels[offset + 1] * weight;
                    b += originalPixels[offset + 2] * weight;
                }
            }

            let destOffset = (y * width + x) * 4;
            outputPixels[destOffset] = r;
            outputPixels[destOffset + 1] = g;
            outputPixels[destOffset + 2] = b;
            outputPixels[destOffset + 3] = originalPixels[destOffset + 3]; // 保持相同的 alpha 值
        }
    }

    // 将处理后的图像数据绘制回画布
    context.putImageData(outputImageData, 0, 0);
}


// 获取主色
const getBaseColors = (pixels, colors) => {
    const size = Math.round(pixels.length / 4);
    const rgb = [];

    for (let i = 0, offset, r, g, b, a; i < size; i++) {
        offset = i * 4;
        r = pixels[offset + 0];
        g = pixels[offset + 1];
        b = pixels[offset + 2];
        a = pixels[offset + 3];

        if (typeof a === "undefined" || a >= 200) {
            rgb.push([r, g, b]);
            // if (!(r > 250 && g > 250 && b > 250)) {
            //     rgb.push([r, g, b]);
            // }
        }
    }

    // 获取主色
    // const cmap = Quantize(rgb, colors.length);
    const cmap = Quantize(rgb, 10);
    const palette = cmap ? cmap.palette() : [];
    const repeat = new Map(palette.map(i => [i.join(","), i]));

    // 把主题色替换为目标色
    // const result = palette.map(rgb => {
    //     const distance = colors.map(color => colorDistance(rgb, color.rgb));
    //     const min = Math.min(...distance);
    //     const index = distance.indexOf(min);
    //     const active = colors[index];

    //     return {
    //         rgb: rgb,
    //         hex: colorHex(rgb),
    //         fill: active ? active.hex : undefined,
    //     };
    // });

    // const result = Array.from(repeat.values()).map(rgb => ({
    //     rgb: rgb,
    //     hex: colorHex(rgb),
    //     fill: colorHex(rgb),
    // }));

    // cmap.vboxes.map(i => console.log(i.vbox._count, i.vbox._volume));

    return Array.from(repeat.values());
};

// 取图形
const getShapePaths = async ({ width, height, pixels,place, colors,spliceColorType,spliceChildrenType, callback }) => {
    const size = width * height;

    const places = place.map(i => i.rgb);
    // console.log("colors", colors);

    // 图层分离
    const layers = colors.map(rgb => {
        // const canvas = document.createElement('canvas')
        // canvas.width = width;
        // canvas.height = height;
        const canvas = Canvas.createCanvas(width, height);
        const ctx = canvas.getContext("2d");
        const pixel = ctx.createImageData(width, height);
        // const index = getNearColorIndex(rgb, places);
        // const active = place[index];

        return {
            width: width,
            height: height,
            canvas: canvas,
            ctx: ctx,
            pixel: pixel,
            rgb: rgb,
            hex: colorHex(rgb),
            // fill: active ? active.fill : colorHex(rgb),
            fill: colorHex(rgb),
            count: 0,
        };
    });

    // 按颜色拆分图层
    for (let i = 0; i < size; i++) {
        const offset = i * 4;
        const rgb = [pixels[offset + 0], pixels[offset + 1], pixels[offset + 2]];
        const alpha = pixels[offset + 3];
        const index = getNearColorIndex(
            rgb,
            layers.map(i => i.rgb)
        );
        const active = layers[index];

        // const distance = layers.map(layer => colorDistance(rgb, layer.rgb));
        // const min = Math.min(...distance);
        // const index = distance.indexOf(min);

        if (alpha > 100 && index >= 0 && active) {
            active.count += 1;
            active.pixel.data[offset] = 0;
            active.pixel.data[offset + 1] = 0;
            active.pixel.data[offset + 2] = 0;
            active.pixel.data[offset + 3] = 255;
        }
    }

    // 生成path
    const promises = layers.map(async layer => {
        if (layer.count > 0) {
            layer.ctx.putImageData(layer.pixel, 0, 0);
            let base64Image = layer.canvas.toDataURL('image/png', 1.0)
            let blobFile = dataURLToBlob(base64Image)
            // const buffer = Buffer.from(base64Image);
            const buffer = await blobToArrayBuffer(blobFile);

            // const buffer = layer.canvas.toBuffer("image/png");

            return getSvgPath(layer.width, layer.height, buffer, layer.fill);

            // const buffer = layer.canvas.toBuffer("image/png");
            // const filename = "layer" + layer.color.join("-") + ".png";
            // const filepath = Path.resolve() + "/demo/" + filename;
            // Fs.writeFileSync(filepath, buffer);
            // return Promise.resolve(fullname)
        } else {
            return Promise.resolve("");
        }
    });

    // 下载和预览
    await Promise.all(promises).then(res => {
        const paths = [];
        const colors = [];
        const bodyColors = [];
        const texts = [];
        res.map((i, idx) => {
            const layer = layers[idx];
            if (i && !/d=""/.test(i) && layer) {
                let color = (i.match(/fill="([\w\W]+?)"/) || [])[1];
                const d = (i.match(/d="([\w\W]+?)"/) || [])[1] || "";
                const moves = d.match(/[mM][^mM]+/g);
                let nodeId = random_string()
                // bodyColors.push({ id: nodeId, color})
                // if (color == "#22140e") {
                //     paths.push(`<path d="${d} Z" fill="${color}" id="${nodeId}" />`);
                // } else if (layer.fill == "#fbfbfb") {
                //     //
                // } else {
                // moves.map(d => {
                //     let nodeId = random_string()
                //     paths.push(`<path d="${d} Z" fill="${color}" id="${nodeId}" />`)
                //     bodyColors.push({ id: nodeId, color })
                // });

                // 按针线色置换颜色
                if(spliceColorType===2){
                    color=findClosestColor(hexToRgb(color),places)
                    color=rgbToHex(color)
                }

                // 分割后的子路径path
                let children =[]
                if(spliceChildrenType===2){
                    moves.map((d1, i2) => {
                        let strPath=`<path d="${d1} Z" fill="#333333" fill-rule="evenodd" />`
                        let nodePath=parseToDOM(strPath)[0]
                        let points=100
                        let area = getPathArea(nodePath, points);
                        if(idx==0){
                            console.log("index="+i2+":",area);
                        }
                        let strSvg=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:100%;height:100%" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" id="svg-image">\n${strPath}</svg>`
                        if(area>=100){
                            children.push(strSvg)
                        }
                    });
                    console.log("children:" + idx + "==", children.length);
                }
                // 当前模块的路径 selfPath 
                const selfSvg = `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:100%;height:100%" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" id="svg-image">\n<path d="${d} Z" fill="${color}" fill-rule="evenodd" /></svg>`
                bodyColors.push({ id: nodeId, color, selfSvg, children })
                // 所有路径添加到paths集合中
                paths.push(`<path d="${d} Z" fill="${color}" fill-rule="evenodd" id="${nodeId}" />`);
                // }

                // colors.push(`<rect x="10" y="${colors.length * 30 + 10}" width="30" height="20" fill="${layer.fill}" />`);
                // texts.push(`<text x="50" y="${texts.length * 30 + 25}" fill="#f00" stroke-width="1px" stroke="#fff"  paint-order="stroke"  >${layer.fill}</text>`);
            }
        });

        let images = colorOptions.map(img => {
            return `\n<pattern id="${img.id}" patternUnits="userSpaceOnUse" width="20" height="20">
                    <image id="${img.id}-image" preserveAspectRatio="none" vector-effect="non-scaling-stroke" xlink:href="${img.icon}" x="-10" y="-10" width="40" height="40" transform="rotate(0,10,10)" />
                </pattern>`
        })
        const defs = `<defs>
               ${images.join("")}
            </defs>`
        const background = "";
        // const background = `<rect x="0" y="0" width="${width}" height="${height}" fill="#f00" />`;
        const body = [background, paths.join("\n"), colors.join("\n"), texts.join("\n")].join("\n");
        const temp = `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="max-width:100%;max-height:100%" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" id="svg-image">\n${defs}\n${body}</svg>`;
        // const filepath = Path.resolve() + "/demo/embroidery/layer-output.svg";
        // Fs.writeFileSync(filepath, temp);
        callback({ svg: temp, colors: bodyColors })
    });
};

// const getShapePaths = async ({ width, height, pixels, colors, callback }) => {
//     const size = width * height;

//     // const places = place.map(i => i.rgb);
//     console.log("colors", colors);

//     // 图层分离
//     const layers = colors.map(rgb => {
//         // const canvas = document.createElement('canvas')
//         // canvas.width = width;
//         // canvas.height = height;
//         const canvas = Canvas.createCanvas(width, height);
//         const ctx = canvas.getContext("2d");
//         const pixel = ctx.createImageData(width, height);
//         // const index = getNearColorIndex(rgb, places);
//         // const active = place[index];

//         return {
//             width: width,
//             height: height,
//             canvas: canvas,
//             ctx: ctx,
//             pixel: pixel,
//             rgb: rgb,
//             hex: colorHex(rgb),
//             // fill: active ? active.fill : colorHex(rgb),
//             fill: colorHex(rgb),
//             count: 0,
//         };
//     });

//     // 按颜色拆分图层
//     for (let i = 0; i < size; i++) {
//         const offset = i * 4;
//         const rgb = [pixels[offset + 0], pixels[offset + 1], pixels[offset + 2]];
//         const alpha = pixels[offset + 3];
//         const index = getNearColorIndex(
//             rgb,
//             layers.map(i => i.rgb)
//         );
//         const active = layers[index];

//         // const distance = layers.map(layer => colorDistance(rgb, layer.rgb));
//         // const min = Math.min(...distance);
//         // const index = distance.indexOf(min);

//         if (alpha > 100 && index >= 0 && active) {
//             active.count += 1;
//             active.pixel.data[offset] = 0;
//             active.pixel.data[offset + 1] = 0;
//             active.pixel.data[offset + 2] = 0;
//             active.pixel.data[offset + 3] = 255;
//         }
//     }

//     // 生成path
//     const promises = layers.map(async layer => {
//         if (layer.count > 0) {
//             layer.ctx.putImageData(layer.pixel, 0, 0);
//             let base64Image = layer.canvas.toDataURL('image/png', 1.0)
//             let blobFile = dataURLToBlob(base64Image)
//             // const buffer = Buffer.from(base64Image);
//             const buffer = await blobToArrayBuffer(blobFile);

//             // const buffer = layer.canvas.toBuffer("image/png");

//             return getSvgPath(layer.width, layer.height, buffer, layer.fill);

//             // const buffer = layer.canvas.toBuffer("image/png");
//             // const filename = "layer" + layer.color.join("-") + ".png";
//             // const filepath = Path.resolve() + "/demo/" + filename;
//             // Fs.writeFileSync(filepath, buffer);
//             // return Promise.resolve(fullname)
//         } else {
//             return Promise.resolve("");
//         }
//     });

//     // 下载和预览
//     await Promise.all(promises).then(res => {
//         const paths = [];
//         const colors = [];
//         const bodyColors = [];
//         const texts = [];
//         res.map((i, idx) => {
//             const layer = layers[idx];
//             if (i && !/d=""/.test(i) && layer) {
//                 const color = (i.match(/fill="([\w\W]+?)"/) || [])[1];
//                 const d = (i.match(/d="([\w\W]+?)"/) || [])[1] || "";
//                 const moves = d.match(/[mM][^mM]+/g);
//                 let nodeId = random_string()
//                 // bodyColors.push({ id: nodeId, color})
//                 // if (color == "#22140e") {
//                 //     paths.push(`<path d="${d} Z" fill="${color}" id="${nodeId}" />`);
//                 // } else if (layer.fill == "#fbfbfb") {
//                 //     //
//                 // } else {
//                 // moves.map(d => {
//                 //     let nodeId = random_string()
//                 //     paths.push(`<path d="${d} Z" fill="${color}" id="${nodeId}" />`)
//                 //     bodyColors.push({ id: nodeId, color })
//                 // });

//                 // 分割后的子路径path
//                 let children = moves.map((d1, i2) => {
//                     // if(idx==0){
//                     //     console.log("index="+i2+":",d1);
//                     // }

//                     return `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:100%;height:100%" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" id="svg-image">\n<path d="${d1} Z" fill="#333333" fill-rule="evenodd" /></svg>`
//                 });
//                 // 当前模块的路径 selfPath 
//                 const selfSvg = `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:100%;height:100%" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" id="svg-image">\n<path d="${d} Z" fill="${color}" fill-rule="evenodd" /></svg>`
//                 bodyColors.push({ id: nodeId, color, selfSvg, children })
//                 // 所有路径添加到paths集合中
//                 paths.push(`<path d="${d} Z" fill="${color}" fill-rule="evenodd" filter="url(#blurMe)" transform="scale(1.05)" id="${nodeId}" />`);
//                 // }

//                 // colors.push(`<rect x="10" y="${colors.length * 30 + 10}" width="30" height="20" fill="${layer.fill}" />`);
//                 // texts.push(`<text x="50" y="${texts.length * 30 + 25}" fill="#f00" stroke-width="1px" stroke="#fff"  paint-order="stroke"  >${layer.fill}</text>`);
//             }
//         });

//         let images = colorOptions.map(img => {
//             return `\n<pattern id="${img.id}" patternUnits="userSpaceOnUse" width="20" height="20">
//                     <image id="${img.id}-image" preserveAspectRatio="none" vector-effect="non-scaling-stroke" xlink:href="${img.icon}" x="-10" y="-10" width="40" height="40" transform="rotate(0,10,10)" />
//                 </pattern>`
//         })
//         const defs = `<defs>
//                ${images.join("")}
//             </defs>`
//         const filter = `<filter id="blurMe">
//                 <feGaussianBlur in="SourceGraphic" stdDeviation="5"/>
//             </filter>`
//         const background = "";
//         // const background = `<rect x="0" y="0" width="${width}" height="${height}" fill="#f00" />`;
//         const body = [background, paths.join("\n"), colors.join("\n"), texts.join("\n")].join("\n");
//         const temp = `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="max-width:100%;max-height:100%" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" id="svg-image">\n${filter}\n${defs}\n${body}</svg>`;
//         // const filepath = Path.resolve() + "/demo/embroidery/layer-output.svg";
//         // Fs.writeFileSync(filepath, temp);
//         callback({ svg: temp, colors: bodyColors })
//     });
// };



function dataURLToBlob(fileDataURL) {
    let arr = fileDataURL.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

function blobToArrayBuffer(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsArrayBuffer(blob)
        reader.onload = () => {
            resolve(reader.result);
        }
    })

}

// 按图层保存成png图片
const getShapePngs = async (width, height, pixels, colors, place) => {
    const size = width * height;

    // 图层分离
    const layers = colors.map(rgb => {
        // const canvas = document.createElement('canvas')
        // canvas.width = 500;
        // canvas.height = 300;
        const canvas = Canvas.createCanvas(image.width, image.height);
        const ctx = canvas.getContext("2d");
        const pixel = ctx.createImageData(width, height);

        return {
            width: width,
            height: height,
            canvas: canvas,
            ctx: ctx,
            pixel: pixel,
            rgb: rgb,
            hex: colorHex(rgb),
            fill: colorHex(rgb),
            count: 0,
        };
    });

    const rgbs = layers.map(i => i.rgb);

    // 按颜色拆分图层
    for (let i = 0; i < size; i++) {
        const offset = i * 4;
        const rgb = [pixels[offset + 0], pixels[offset + 1], pixels[offset + 2]];
        const alpha = pixels[offset + 3];
        const index = getNearColorIndex(rgb, rgbs);
        const active = layers[index];

        // const distance = layers.map(layer => colorDistance(rgb, layer.rgb));
        // const min = Math.min(...distance);
        // const index = distance.indexOf(min);

        layers.map(layer => {
            if (alpha > 100 && index >= 0 && active == layer) {
                layer.count += 1;
                layer.pixel.data[offset] = 255;
                layer.pixel.data[offset + 1] = 255;
                layer.pixel.data[offset + 2] = 255;
                layer.pixel.data[offset + 3] = 255;
            } else {
                layer.pixel.data[offset] = 0;
                layer.pixel.data[offset + 1] = 0;
                layer.pixel.data[offset + 2] = 0;
                layer.pixel.data[offset + 3] = 255;
            }
        });
    }

    // 生成path
    const promises = layers.map(layer => {
        if (layer.count > 0) {
            layer.ctx.putImageData(layer.pixel, 0, 0);

            // const buffer = layer.canvas.toBuffer("image/png");
            // return getSvgPath(layer.width, layer.height, buffer, layer.fill);

            const buffer = layer.canvas.toBuffer("image/png");
            const filename = "layer-output-" + layer.fill + ".png";
            const filepath = Path.resolve() + "/demo/embroidery/" + filename;
            Fs.writeFileSync(filepath, buffer);
            return Promise.resolve(filename);
        } else {
            return Promise.resolve("");
        }
    });

    await Promise.all(promises).then(res => { });
};

// 像素分割
const getShapeImage = async (width, height, pixels, colors) => {
    const size = width * height;

    // 图层分离
    const layers = colors.map(color => {
        const canvas = document.createElement('canvas')
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext("2d");
        const pixel = ctx.createImageData(width, height);
        return {
            width: width,
            height: height,
            canvas: canvas,
            ctx: ctx,
            pixel: pixel,
            rgb: color.rgb,
            hex: color.hex,
            fill: color.fill,
            count: 0,
        };
    });

    // 相同颜色合并
    for (let i = 0; i < size; i++) {
        const offset = i * 4;
        const rgb = [pixels[offset + 0], pixels[offset + 1], pixels[offset + 2]];
        const alpha = pixels[offset + 3];
        const distance = layers.map(layer => colorDistance(rgb, layer.rgb));
        const min = Math.min(...distance);
        const index = distance.indexOf(min);
        const active = layers[index];

        if (alpha > 100 && index >= 0 && active) {
            const rgb = colorRgb(active.fill);
            active.count += 1;
            active.pixel.data[offset] = rgb[0];
            active.pixel.data[offset + 1] = rgb[1];
            active.pixel.data[offset + 2] = rgb[2];
            active.pixel.data[offset + 3] = 255;
        }
    }

    const canvas = Canvas.createCanvas(width, height);
    const ctx = canvas.getContext("2d");
    const filepath = Path.resolve() + "/demo/embroidery/layer-output.png";

    // 合成path
    layers.map(layer => {
        if (layer.count > 0) {
            layer.ctx.putImageData(layer.pixel, 0, 0);
            // 粘贴图片
            ctx.drawImage(layer.canvas, 0, 0, layer.width, layer.height);
        } else {
            return Promise.resolve("");
        }
    });

    const buffer = canvas.toBuffer("image/png");
    Fs.writeFileSync(filepath, buffer);

    // // 下载和预览
    // await Promise.all(promises).then(res => {
    //     const paths = [];
    //     const colors = [];
    //     res.map((i, idx) => {
    //         const layer = layers[idx];
    //         if (i && !/d=""/.test(i) && layer) {
    //             paths.push(i);
    //             colors.push(`<rect x="10" y="${colors.length * 30}" width="60" height="20" fill="${layer.hex}" />`);
    //         }
    //     });

    //     const temp = `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">\n${paths.join("\n")}\n${colors.join("\n")}</svg>`;
    //     const filepath = Path.resolve() + "/demo/layer-output.svg";

    //     Fs.writeFileSync(filepath, temp);
    // });
};

// const name = "demo/embroidery/cat-transparent.png";
const name = "demo/embroidery/cat-simple.png";
// const name = "demo/embroidery/cat-white.png";

// 加载本地资源
// loadLocalImage(Path.join(Path.resolve(), name)).then(image => {
//     console.log("-----------------------",image);

//     // 取像素
//     const pixels = getImageData(image);

//     const place = [
//         { fill: "#FFFFFF", hex: "#FFFFFF", rgb: [255, 255, 255] },
//         { fill: "#000000", hex: "#000000", rgb: [0, 0, 0] },
//         { fill: "#96A1A8", hex: "#96A1A8", rgb: [150, 161, 168] },
//         { fill: "#A67843", hex: "#A67843", rgb: [166, 120, 67] },
//         { fill: "#FFCC00", hex: "#FFCC00", rgb: [255, 204, 0] },
//         { fill: "#E25C27", hex: "#E25C27", rgb: [226, 92, 39] },
//         { fill: "#CC3366", hex: "#CC3366", rgb: [204, 51, 102] },
//         { fill: "#CC3333", hex: "#CC3333", rgb: [204, 51, 51] },
//         { fill: "#660000", hex: "#660000", rgb: [102, 0, 0] },
//         { fill: "#333366", hex: "#333366", rgb: [51, 51, 102] },
//         { fill: "#005397", hex: "#005397", rgb: [0, 83, 151] },
//         { fill: "#3399FF", hex: "#3399FF", rgb: [51, 153, 255] },
//         { fill: "#6B5294", hex: "#6B5294", rgb: [107, 82, 148] },
//         { fill: "#01784E", hex: "#01784E", rgb: [1, 120, 78] },
//         { fill: "#7BA35A", hex: "#7BA35A", rgb: [123, 163, 90] },
//     ];

//     // 取主色
//     const colors1 = getBaseColors(pixels, place);

//     // 取主色2
//     // const colors2 = gap(pixels, place);

//     // console.log(colors1, colors2);

//     // slicTest(pixels, image.width, image.height);

//     // const colors = place;

//     // 按主色，取图形
//     getShapePaths(image.width, image.height, pixels, colors1, place);
//     // getShapePngs(image.width, image.height, pixels, colors1, place);

//     // 按主色，分割图片
//     // getShapeImage(image.width, image.height, pixels, colors);

//     // console.log(shapes);

//     // doLayered(image);
//     // getBaseColors(image);
// });


export function loadImage({ image, spliceColorType,spliceChildrenType, callback }) {
    // console.log("-----------------------", image);

    // 取像素
    const pixels = getImageData(image);
    const place=placeOptions
    
    console.log("pixels",pixels.length);
    if(pixels.length>=10000000){
        callback({error:"图片不能超过200万像素"})
        return false
    }
    // 取主色
    let colors = []
    colors = getBaseColors(pixels, place);

    // // 按针线色 从针线色中取最接近的颜色
    // if (spliceColorType === 2) {
    //     let palette = place.map(i => i.rgb);
    //     colors = colors.map(c => {
    //         return findClosestColor(c,palette)
    //     });
    //     colors=colors.filter((item, index) => {
    //         return colors.findIndex(e=>JSON.stringify(e)===JSON.stringify(item)) === index
    //     })
    // }
    console.log("-----------------------", image.width, image.height);

    // 按主色，取图形
    getShapePaths({ width: image.width, height: image.height, pixels, colors, place,spliceColorType,spliceChildrenType, callback });
    // getShapePngs(image.width, image.height, pixels, colors1, place);
}

